package com.caisejingyu.whales.home.widget

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.widget.ImageView
import com.caisejingyu.whales.home.R

/**
 * 部分透明图片
 */
class PartlyTransparentImageView(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : ImageView(context, attrs, defStyleAttr) {
    constructor(context: Context) : this(context, null, 0)

    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)

    private var transparentRadius = 0f
    private var transparentMarginLeft = 0f
    private var transparentMarginRight = 0f
    private var transparentMarginTop = 0f
    private var transparentMarginBottom = 0f

    private var xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_IN) // 设置 Xfermode

    init {
        if (attrs != null) {
            val mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.PartlyTransparentImageView)
            transparentRadius = mTypedArray.getDimension(R.styleable.PartlyTransparentImageView_transparent_radius, transparentRadius)
            transparentMarginLeft = mTypedArray.getDimension(R.styleable.PartlyTransparentImageView_transparent_margin_left, transparentMarginLeft)
            transparentMarginRight = mTypedArray.getDimension(R.styleable.PartlyTransparentImageView_transparent_margin_right, transparentMarginRight)
            transparentMarginTop = mTypedArray.getDimension(R.styleable.PartlyTransparentImageView_transparent_margin_top, transparentMarginTop)
            transparentMarginBottom = mTypedArray.getDimension(R.styleable.PartlyTransparentImageView_transparent_margin_bottom, transparentMarginBottom)

            mTypedArray.recycle()
        }
    }

    private val paint: Paint = Paint()

    init {
        paint.style = Paint.Style.FILL_AND_STROKE
        paint.color = Color.TRANSPARENT
        paint.isAntiAlias = true
    }

    override fun onDraw(canvas: Canvas?) {

        if (canvas != null) {
            val saved = canvas.saveLayer(null, null, Canvas.ALL_SAVE_FLAG)
            super.onDraw(canvas)
            paint.xfermode = xfermode
            var left = transparentMarginLeft
            var right = measuredWidth - transparentMarginRight
            var top = transparentMarginTop
            var bottom = measuredHeight - transparentMarginBottom
            canvas.drawRoundRect(RectF(left, top, right, bottom),
                    transparentRadius, transparentRadius, paint) //绘制透明区域
            paint.xfermode = null // 用完及时清除 Xfermode
            canvas.restoreToCount(saved)
        }
    }
}